# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if k==1:
            return head
        l=0
        t=head
        while t:
            l+=1
            t=t.next
        n=l//k
        def reverse(h,k):
            s=h.next.next
            tail=h.next
            for i in range(k-1):
                real_next=s.next
                temp=h.next
                h.next=s
                s.next=temp
                s=real_next
            tail.next=real_next
            return tail
        dummy=ListNode(next=head)
        now=dummy
        for _ in range(n):
            now=reverse(now,k)
        return dummy.next


'''
执行用时：
56 ms
, 在所有 Python3 提交中击败了
62.95%
的用户
内存消耗：
15.6 MB
, 在所有 Python3 提交中击败了
41.40%
的用户
'''